package com.hframe.plugin.ueditor;

import com.hframe.http.client.HttpUpload;
import com.hframe.other.MsgException;
import com.hframe.type.TString;
import org.apache.tomcat.util.http.fileupload.FileItem;

import javax.servlet.ServletContext;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;

/**
 * Created by heqian on 17-10-25.
 */
public class UploadFile extends HttpUpload {
    private final ServletContext context;
    private final Long maxSize;
    private final String pathFormat;
    private final ArrayList<TString> allowFiles;

    private String fileName = null;
    private File uploadFile = null;
    private Long size;
    private String uploadName;

    public UploadFile(ServletContext context, String pathFormat, Long maxSize, ArrayList<TString> allowFiles) {
        super(context.getRealPath(pathFormat));
        this.context = context;
        this.pathFormat = pathFormat;
        this.maxSize = maxSize;
        this.allowFiles = allowFiles;
    }

    @Override
    protected File startUploadCall(FileItem item) throws Exception {
        size = item.getSize();
        if (maxSize < size) {
            throw new MsgException("");
        }

        uploadName = item.getName();
        String allow = uploadName.substring(uploadName.lastIndexOf("."));
        isAllowFile(allow);

        if (null == fileName) {
            fileName = new Date().toString();
        }
        fileName += allow;

        uploadFile = new File(savePath + "/" + fileName);
        return uploadFile;
    }

    private void isAllowFile(String allow) throws MsgException {
        if (null != allowFiles) {
            if (null != allow) {
                for (TString item : allowFiles) {
                    if (item.get().toLowerCase().equals(allow.toLowerCase())) {
                        return;
                    }
                }
            }
            throw new MsgException("上传格式出错");
        }
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public File getUploadFile() {
        return uploadFile;
    }

    public Long getSize() {
        return size;
    }

    public void setSize(Long size) {
        this.size = size;
    }

    public String getUploadName() {
        return uploadName;
    }
}
